<template>
  <div class="left-content win-flex-column">
    <div class="win-flex-row total_content">
      <div class="totalPopularityCount mr5">
        <span class="mr3">读名字个数</span>
        <el-select filterable style="width: 90px;" size="mini" placeholder="读名字个数" v-model="pageConfig.nameSize">
          <el-option :key="'nameSize_' + index" v-for="(item, index) in nameSizeList" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </div>
      <div class="currentlyOnlineCount">
        <span class="mr3">人数</span>
        <el-tag class="currentlyOnlineCount_tag" effect="dark">
          {{ currentlyOnlineCount }}
        </el-tag>
      </div>
    </div>
    <div class="win-flex-row open_content mt5">
      <el-button class="w100Rate" type="primary" size="mini" @click="openBarrageTool">打开弹幕工具</el-button>
      <el-button v-if="wsConnected" class="ml5" type="success" size="mini" icon="el-icon-connection">已连接弹幕工具</el-button>
      <el-button v-else class="ml5" type="danger" size="mini" icon="el-icon-refresh"
        @click="reconnectWebSocket">重连弹幕工具</el-button>
    </div>
    <div class="user_interaction flex-1 item-content">
      <el-divider class="header-title">用户互动</el-divider>
      <el-table size="mini" ref="userBarrageTable" :data="userBarrageDataList" height="calc(100% - 30px)" border>
        <el-table-column prop="nickName" label="名字" width="100">
        </el-table-column>
        <el-table-column prop="content" label="内容">
        </el-table-column>
      </el-table>
    </div>
    <div class="anchor_barrage flex-1 item-content">
      <el-divider class="header-title">主播弹幕</el-divider>
      <el-table size="mini" ref="anchorBarrageTable" :data="anchorBarrageDataList" height="calc(100% - 30px)" border>
        <el-table-column prop="nickName" label="名字" width="100">
        </el-table-column>
        <el-table-column prop="content" label="内容">
        </el-table-column>
      </el-table>
    </div>
    <div class="user_enter flex-1 item-content">
      <el-divider class="header-title">用户进入</el-divider>
      <el-table size="mini" ref="userEnterTable" :data="userEnterDataList" height="calc(100% - 30px)" border>
        <el-table-column prop="nickName" label="名字" width="100">
        </el-table-column>
        <el-table-column prop="content" label="内容">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { createWebsocket, closeWebsocket } from "@/utils/webSocketUtil";
import { liveInfoType, nameSizeList } from "@/enum/enums";
import { updateUserCount } from "@/api/live/live";
import { mapActions } from "vuex";
import { EventBus } from '@/event-bus.js';
import { userEnterMatch } from './mixins/userEnterMatch';
import { keyWordMatch } from './mixins/keyWordMatch';
import { smartReplyMatch } from './mixins/smartReplyMatch';
import { randomAudioMatch } from './mixins/randomAudioMatch';
import { openBarrageAssistant } from '@/api/common/assistant';
import { getUUID } from "@/utils/util";
export default {
  name: 'Left',
  mixins: [userEnterMatch, keyWordMatch, smartReplyMatch, randomAudioMatch],
  data() {
    return {
      currentlyOnlineCount: 0,
      totalPopularityCount: 0,
      maxTableSize: 100,
      userEnterDataList: [],
      userBarrageDataList: [],
      anchorBarrageDataList: [],
      ws: null,
      liveInfoType,
      nameSizeList,
      wsConnected: false,
      reconnectTimer: null,
      reconnectAttempts: 0,
      maxReconnectAttempts: 30,
      reconnectInterval: 5000,
      liveStatus: 0
    };
  },
  created() {
    EventBus.$on("changeLiveStatus", (status) => {
      //开启了直播
      this.liveStatus = status;
      if (status == 1) {
        this.initWebSocket();
      } else if (status == 0) {
        this.currentlyOnlineCount = 0;
        this.totalPopularityCount = 0;
        this.userEnterDataList = [];
        this.userBarrageDataList = [];
        this.anchorBarrageDataList = [];
        this.clearReconnectTimer();
        closeWebsocket(this.ws);
        this.wsConnected = false;
      }
    });
  },
  beforeDestroy() {
    EventBus.$off('changeLiveStatus');
    this.clearReconnectTimer();
    closeWebsocket(this.ws);
  },
  computed: {
    pageConfig() {
      return this.$store.state.page.config;
    }
  },
  watch: {},
  methods: {
    ...mapActions({
      setLiveCurrentlyOnlineCount: 'setLiveCurrentlyOnlineCount',
      setLiveTotalPopularityCount: 'setLiveTotalPopularityCount',
    }),
    openBarrageTool() {
      openBarrageAssistant().then(res => {
        if (res.code == 200) {
          this.$message.success('开启成功');
        } else {
          this.$message.error('开启失败');
        }
      });
    },
    scrollToBottom(tableRefName) {
      const table = this.$refs[tableRefName];
      if (table) {
        const bodyWrapper = table.$el.querySelector('.el-table__body-wrapper');
        if (bodyWrapper) {
          bodyWrapper.scrollTop = bodyWrapper.scrollHeight;
        }
      }
    },
    clearReconnectTimer() {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
      }
    },
    reconnectWebSocket() {
      this.clearReconnectTimer();
      this.reconnectAttempts = 0;
      this.initWebSocket();
    },
    scheduleReconnect() {
      this.clearReconnectTimer();

      if (this.liveStatus !== 1) {
        return;
      }

      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectTimer = setTimeout(() => {
          this.reconnectAttempts++;
          console.log(`尝试重新连接WebSocket，第${this.reconnectAttempts}次尝试`);
          this.initWebSocket();
        }, this.reconnectInterval);
      } else {
        console.error('WebSocket重连失败，已达到最大重试次数');
        this.$message.error('弹幕连接失败，请手动点击重连按钮');
      }
    },
    initWebSocket() {
      // 先关闭之前的连接
      if (this.ws) {
        closeWebsocket(this.ws);
      }

      this.wsConnected = false;

      createWebsocket(window.AudioConfig.websocketUrl, {}, {
        onopen: (ws) => {
          this.ws = ws;
          this.wsConnected = true;
          this.reconnectAttempts = 0;
          console.log('WebSocket连接成功');
        },
        onmessage: (ws, event) => {
          let resultData = JSON.parse(event.data);
          const { Type, Data } = resultData;
          if (Type == this.liveInfoType.userEnter.type) {
            this.userEnterDataList.push({
              nickName: Data.User.NickName,
              content: '进入直播间',
              hasGen: false,
              timestamp: Date.now()
            });
            if (this.userEnterDataList.length > this.maxTableSize) {
              this.userEnterDataList.shift();
            }
            this.$nextTick(() => {
              this.scrollToBottom('userEnterTable');
            });
          } else if (Type == this.liveInfoType.userBarrage.type) {
            if (Data.User.IsAnchor) {
              this.anchorBarrageDataList.push({
                nickName: Data.User.NickName,
                content: Data.Content,
                timestamp: Date.now()
              });
              if (this.anchorBarrageDataList.length > this.maxTableSize) {
                this.anchorBarrageDataList.shift();
              }
              this.$nextTick(() => {
                this.scrollToBottom('anchorBarrageTable');
              });
            } else {
              this.userBarrageDataList.push({
                id: getUUID(),
                nickName: Data.User.NickName,
                content: Data.Content,
                timestamp: Date.now(),
                hasGen: false,
                hasReply: false
              });
              if (this.userBarrageDataList.length > this.maxTableSize) {
                this.userBarrageDataList.shift();
              }
              this.$nextTick(() => {
                this.scrollToBottom('userBarrageTable');
              });
            }
          } else if (Type == this.liveInfoType.userCount.type) {
            this.currentlyOnlineCount = Data.CurrentlyOnlineCount;
            this.totalPopularityCount = Data.TotalPopularityCount;
            updateUserCount({
              userCount: this.currentlyOnlineCount,
            });
            this.setLiveCurrentlyOnlineCount(this.currentlyOnlineCount);
            this.setLiveTotalPopularityCount(this.totalPopularityCount);
          }
        },
        onclose: () => {
          console.log('WebSocket连接关闭');
          this.wsConnected = false;
          this.scheduleReconnect();
        },
        onerror: () => {
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.left-content {
  border: 1px solid var(--color-border-first);
  padding: 10px;

  .currentlyOnlineCount_tag {
    min-width: 65px;
    text-align: center;
  }

  ::v-deep .el-divider--horizontal {
    margin: 14px 0 !important;
  }

  .item-content {
    height: 33%;
  }

  .ml5 {
    margin-left: 5px;
  }
}
</style>
